<?php

namespace App\Library;

use App\Models\Recommend;
use App\Models\Member;
use App\Models\Property;
use App\Models\UserRelations;
use Exception;
use DB;

/**
 * 写入关系线（待完善）.
 * 必须放入事物中
 */
class WriteRelation
{
    /**
     *  入口方法
     * 涉及的数据库必须是innodb引擎.
     */
    public static function entry($user_id)
    {
        try {
            $user = Member::find($user_id);
            if (!$user) {
                throw new Exception('用户不存在');
            }
            if ($user->PID == 0) {
                throw new Exception('没有推荐人');
            }
            $parent = Member::find($user->PID);
            if (!$parent) {
                throw new Exception('推荐人不存在');
            }
            $buser = Recommend::where('buserID', $user_id)->first();
            if ($buser) {
                throw new Exception('该用户已进入推荐线');
            }
            // 启动事务
            //DB::beginTransaction();

            $msg = self::execute($user, $parent);

            //DB::commit();
        } catch (Exception $e) {
            //DB::rollback();
            $msg = $e->getMessage();
        }

        return $msg;
    }

    /**
     * 根据推荐人身份执行不同的流程.
     */
    private static function execute(Member $user, Member $parent)
    {
        if ($parent->PID == -1) { //推荐人为原点
            $res = self::origin($user, $parent);
        } else {
            switch ($parent->type) {
                case 1: //推荐人为代理商
                    $res = self::agent($user, $parent);
                    break;
                case 2:  //推荐人为商家
                    $res = self::seller($user, $parent);
                    break;
                default:
                    throw new Exception('推荐人身份不正确');
                    break;
            }
        }

        if ($res === true) {
            //确认身份
            $user->update(['attestation' => 7]);
            //生成资产
            $result = self::createProperty($user->userID);
            if ($result === true) {
                return true;
            }
        }
    }

    /**
     * 原点执行流程.
     */
    private static function origin(Member $user, Member $parent)
    {
        $data = [];
        $data['userID'] = $parent->userID; //推荐人
        $data['buserID'] = $user->userID; //被推荐人
        $data['cuserID'] = $parent->userID; //上一级推荐人
        $data['type'] = 2;
        $data['time'] = time();

        $res = Recommend::create($data);
        if ($res) {
            UserRelations::create([
                'userID' => $user->userID,
                'auserID' => $parent->userID,
                'type' => 3,
                'time' => time(),
            ]);
            UserRelations::create([
                'userID' => $user->userID,
                'auserID' => 0,
                'type' => 4,
                'time' => time(),
            ]);

            return true;
        }
    }

    /**
     * 代理商执行流程.
     */
    private static function agent(Member $user, Member $parent)
    {
        $data = [];
        $data['userID'] = $parent->userID; //推荐人
        $data['buserID'] = $user->userID; //被推荐人
        $data['cuserID'] = $parent->userID; //上一级推荐人
        $data['type'] = 2;
        $data['time'] = time();

        $res = Recommend::create($data);
        if ($res) {
            UserRelations::create([
                'userID' => $user->userID,
                'auserID' => $parent->uesrID,
                'type' => 3,
                'time' => time(),
            ]);
            UserRelations::create([
                'userID' => $user->userID,
                'auserID' => $parent->PID,
                'type' => 4,
                'time' => time(),
            ]);

            return true;
        }
    }

    /**
     * 商家执行流程.
     */
    private static function seller(Member $user, Member $parent)
    {
        $data['userID'] = $parent->userID; //推荐人
        $data['buserID'] = $user->userID; //被推荐人
        $data['cuserID'] = Recommend::where('buserID', $parent->userID)->value('cuserID'); //上一级推荐人
        $data['type'] = 2;
        $data['time'] = time();

        $res = Recommend::create($data);
        if ($res) {
            UserRelations::create([
                'userID' => $user->userID,
                'auserID' => $parent->uesrID,
                'type' => 3,
                'time' => time(),
            ]);
            UserRelations::create([
                'userID' => $user->userID,
                'auserID' => $data['cuserID'],
                'type' => 4,
                'time' => time(),
            ]);

            return true;
        }
    }

    /**
     * 插入资产数据.
     */
    private static function createProperty($userID)
    {
        $check = Property::where('userID', $userID)->whereIn('type', [5, 7, 9])->first();
        if ($check) {
            throw new Exception('资产已存在！');
        }
        Property::create([
            'userID' => $userID, 'name' => '会员收益', 'type' => 5, 'value' => 0, 'status' => 1, 'time' => time(),
        ]);
        Property::create([
            'userID' => $userID, 'name' => '商家管理收益', 'type' => 7, 'value' => 0, 'status' => 1, 'time' => time(),
        ]);
        Property::create([
            'userID' => $userID, 'name' => '店铺收益', 'type' => 9, 'value' => 0, 'status' => 1, 'time' => time(),
        ]);

        return true;
    }
}
